import { FC, ReactElement, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import { flexCenter } from "../../BUI/styled";
import { Form, Input, Button, FormInstance } from "antd";
import {
  NotificationSuccess,
  NotificationWarn,
} from "../../common/Notification";
import {
  createSource,
  Source,
  updateSource as updateSourceAPI,
} from "../../../api/source";
import { objToArr } from "../PokerManage/EditPoker";

interface IProps {
  handleFile: (source: Omit<Source, "owner" | "sender">) => any;
  handleUpdate: (updateField: Partial<Source>) => void;
  updateSource: Partial<Source>;
}

const Upload: FC<IProps> = ({
  handleFile,
  updateSource,
  handleUpdate,
}): ReactElement => {
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const form = useRef<FormInstance>(null);

  useEffect(() => {
    console.log("updateSource", updateSource);
    if (updateSource._id) {
      const antdForm = {
        name: updateSource.name,
        description: updateSource.description,
      };
      form.current?.setFields(objToArr(antdForm));
    } else {
      form.current?.resetFields(["name", "description"]);
      setFile(null);
    }
  }, [updateSource]);

  const fileChange: React.ChangeEventHandler<HTMLInputElement> = e => {
    const { files } = e.target;
    if (files && files.length) {
      console.log(files[0]);
      setFile(files[0] as File);
    }
  };

  const onFinish = async (values: any) => {
    if (!updateSource._id && !file)
      return NotificationWarn({ message: "需要上传资源" });
    setLoading(true);
    const formData = new FormData();
    // @ts-ignore
    formData.append("file", file);
    const params = { ...values, file };
    for (const [key, value] of Object.entries(values)) {
      formData.append(key, value as string);
    }
    if (updateSource._id) formData.append("_id", updateSource._id);
    console.log(params);

    const func = updateSource._id ? updateSourceAPI : createSource;

    // @ts-ignore
    const { data } = await func(formData);

    if (data) {
      NotificationSuccess({ message: data.message });
      form.current?.resetFields(["name", "description"]);

      if (updateSource._id) {
        handleUpdate(data.updateField);
      } else handleFile({ _id: data.sourceId, ...values, file: file!.name });
    }
    setLoading(false);
  };

  return (
    <Container>
      <FileWrap>
        <input type='file' onChange={fileChange} />
        <span>{file ? file.type : updateSource.file || "点击上传"}</span>
      </FileWrap>
      <Form
        ref={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
      >
        <Form.Item
          label='资源名'
          name='name'
          rules={[{ required: true, message: "必须填写资源名" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label='资源描述'
          name='description'
          rules={[{ required: true, message: "必须填写资源描述" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item>
          <Button loading={loading} type='primary' htmlType='submit'>
            {updateSource._id ? "更新" : "创建"}
          </Button>
        </Form.Item>
      </Form>
    </Container>
  );
};

export default Upload;

const FileWrap = styled.div`
  position: relative;
  width: 100%;
  height: 5rem;
  border-radius: 5px;
  background-color: #eee;
  text-align: center;
  margin-bottom: 1rem;
  ${flexCenter};

  & > input {
    position: absolute;
    width: 100%;
    height: 100%;
    cursor: pointer;
    opacity: 0;
  }
`;

const Container = styled.div``;
